package com.example.servlet;

import com.example.Service.CommentService;
import com.example.pojo.Comment;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LikeCommentServlet", value = "/likeComment")
public class LikeCommentServlet extends HttpServlet {
    private final CommentService commentService = new CommentService();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有域名跨域，生产环境可指定具体域名
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();

        try {
            int commentId = Integer.parseInt(request.getParameter("commentId"));
            String userId = request.getParameter("userId");

            int affectedRows = commentService.addLikeComment(commentId, userId);
            if (affectedRows > 0) {
                // 查询最新的评论状态（点赞数 + 是否已点赞）
                Comment comment = commentService.getCommentById(commentId);
                boolean newIsLiked = commentService.isLiked(commentId, userId);

                // 修复：用 Java 8 兼容的 HashMap 替代 Map.of()
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("newLikeNum", comment.getLikeNum());
                dataMap.put("newIsLiked", newIsLiked);
                result.put("data", dataMap); // 放入结果集

                result.put("code", 200);
                result.put("msg", "操作成功");
            } else {
                result.put("code", 400);
                result.put("msg", "操作失败（评论不存在）");
            }
        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "参数错误（commentId 必须为数字）");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "服务器错误：" + e.getMessage());
        }

        response.getWriter().write(gson.toJson(result));
    }
}